package com.gec.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.gec.entity.OrderItem;
import com.gec.entity.Product;
import com.gec.utils.C3P0Utils;

public class OrderItemDao {
	/**
     * 添加订单中商品的方法
     * @param orderItem
     * @return
     */
	QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
    public int addOrderItem(OrderItem orderItem){
	String sql="insert into OrderItem values(?,?,?,?,?)";
	Object[] arr={orderItem.getItemId(),orderItem.getCount(),orderItem.getSubtotal(),
			orderItem.getProduct().getPid(),orderItem.getOid()};
	int n=0;
	try {
		n = queryRunner.update(sql,arr);
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return n;	
    }
    
    /**
     * 	根据商品订单id查询对应的订单的商品信息
     * @param oid
     * @return
     */
    public List<OrderItem> getOrderItemByOid(String oid){
	List<OrderItem> list=null;
	String sql="select * from OrderItem where oid=?";
	try {
		list=queryRunner.query(sql, new BeanListHandler<OrderItem>(OrderItem.class),oid);
		//执行完这个sql语句后 会见这个返回结果的uid复制给我们product数组
		List<Product> list1=queryRunner.query(sql, new BeanListHandler<Product>(Product.class),oid);
		
		ProductDao productDao=new ProductDao();
		for(int i=0;i<list.size();i++){
			Product product = productDao.getProductByPid(list1.get(i).getPid());	
			list.get(i).setProduct(product);
		}
	
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return list;
    }

	public int deleteOrderItemByOid(String oid) {
		String sql="delete from orderitem where oid= ?";
		int n=0;
		try {
			n = queryRunner.update(sql,oid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return n;
		
	}

}
